我正在一个项目中,要求用户输入一个字符串,然后通过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;
    }


这是我的笔记本电脑。

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

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

};


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

最佳答案

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

另外,我会避免泛型

using namespace std;


因为它达到了首先拥有名称空间的目的。通常最好精确指定要使用的类。因此:

using std::string;


更好。

07-24 09:51
查看更多