C++ 关于通过Get和Set方法传递字符串
我正在处理一个项目,该项目要求用户输入一个字符串,然后通过get和set函数简单地显示该字符串。但是,我在让用户输入字符串,然后将其传递给get和set函数时遇到了问题。这是我的密码: 这是我的主页。cpp:C++ 关于通过Get和Set方法传递字符串,c++,string,C++,String,我正在处理一个项目,该项目要求用户输入一个字符串,然后通过get和set函数简单地显示该字符串。但是,我在让用户输入字符串,然后将其传递给get和set函数时遇到了问题。这是我的密码: 这是我的主页。cpp: #include "stdafx.h" #include <iostream> #include "Laptop.h" #include<string> using namespace std; int main() { Laptop Brand;
#include "stdafx.h"
#include <iostream>
#include "Laptop.h"
#include<string>
using namespace std;
int main()
{
Laptop Brand;
string i;
cout << "Enter your brand of laptop : ";
cin >> i;
Brand.setbrand (i);
return 0;
}
#包括“stdafx.h”
#包括
#包括“Laptop.h”
#包括
使用名称空间std;
int main()
{
笔记本电脑品牌;
第i串;
cout>i;
Brand.setbrand(i);
返回0;
}
这是我的笔记本电脑。cpp:
#include "stdafx.h"
#include <iostream>
#include "Laptop.h"
#include <string>
using namespace std;
void Laptop::setbrand(string brand)
{
itsbrand = brand;
}
string Laptop::getbrand()
{
return itsbrand;
}
#包括“stdafx.h”
#包括
#包括“Laptop.h”
#包括
使用名称空间std;
void笔记本电脑::setbrand(字符串品牌)
{
品牌=品牌;
}
string Laptop::getbrand()
{
回归品牌;
}
这是我的笔记本电脑。h:
#include<string>
class Laptop
{
private :
string itsbrand;
public :
void setbrand(string brand);
string getbrand();
};
#包括
班级笔记本电脑
{
私人:
品牌;
公众:
void-setbrand(字符串品牌);
字符串getbrand();
};
在我的laptop.cpp中,我的setbrand和getbrand有错误。他们说getbrand和setbrand不兼容。我很确定这与我通过参数传递字符串有关。有什么想法吗?这里的好办法是在头文件中使用
std::string
而不是string
:
class Laptop
{
private :
std::string itsbrand;
public :
void setbrand(std::string brand);
std::string getbrand();
};
与其他文件不同,您没有使用命名空间std的
。实际上,我建议在任何地方都使用std::string
。它更安全,可以避免以后出现更严重的问题。您没有在laptop.h
文件中包含正确的命名空间,因此编译器无法在当前(全局)命名空间中找到任何声明的string
类。只需在文件的开头使用std::string,代码>
顺便说一句,我会避免泛型
using namespace std;
因为它首先违背了拥有名称空间的目的。通常最好确切地指定您使用的类的类型。因此:
using std::string;
更好。您能发布准确的错误和行吗?另外,通常最好通过常量引用传递std::string
,并使成员函数不修改对象常量。至于错误,标头需要的是std::string
,而不是string
。不过,我不知道这是否是您描述的错误。get brand也应该有以下签名:string getbrand()const
@MikeD,int
在空白处停止,而std::string
在空白处停止。有什么区别吗?@MikeD,是的,但是5465
对于int
只读取54。在我看来,没有语义上的区别。我会将它改为“读取带有cin>
的字符串,在空格处停止”。我一直在尝试使用:Thank you Jueecy将字符串传递给setbrand函数,这非常有帮助。永远不要建议在标题中添加“using namespace”。在字符串变量和方法参数前面键入“std::”不会使程序员丧命。“使用bug进行跟踪所花费的时间远远超过直接键入名称空间所花费的时间。@jmucchiello你确实是对的,只是不鼓励这样做,”我的回答修改了。