0

我正在做一个项目,要求用户输入一个字符串,然后通过 get 和 set 函数简单地显示字符串。但是,实际上让用户输入字符串然后将它们传递给 get 和 set 函数时,我遇到了问题。这是我的代码:这是我的 Main.cpp :

#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;
}

这是我的 Laptop.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;
    }

这是我的 notebook.h :

#include<string>
class Laptop
{
private :
    string itsbrand;

public :
    void setbrand(string brand);
    string getbrand();

};

在我的 notebook.cpp 中,setbrand 和 getbrand 出现错误。他们说 getbrand 和 setbrand 不兼容。我很确定这与我通过参数传递一个字符串有关。有任何想法吗?

4

2 回答 2

1

这里好的解决方法是使用std::string而不是string在头文件中:

class Laptop
{
private :
    std::string itsbrand;

public :
    void setbrand(std::string brand);
    std::string getbrand();
};

与您没有的其他文件不同using namespace std。我实际上建议只std::string在任何地方使用。它更安全,并且可以帮助您避免以后遇到更严重的问题。

于 2013-03-19T01:45:56.100 回答
1

您错过了在文件中包含正确的命名空间,因此编译器在当前(全局)命名空间中laptop.h找不到任何声明的类。string只需在文件的开头放置using std::string;.

在旁注中,我会避​​免通用

using namespace std;

因为它首先违背了拥有命名空间的目的。通常最好明确指定您正在使用哪种类。所以:

using std::string;

更好。

于 2013-03-19T01:48:42.080 回答