“在'无效'之前预期不合格的身份”& “类中的字符串不命名类型”错误

时间:2012-10-28 00:08:41

标签: c++ string class

我不确定如何在这里实施解决方案。

汇编时的错误是: -

error: expected unqualified-id before 'void'

error: 'string' in class 'UserDirectory' does not name a type

error: 'string' in class 'UserDirectory' does not name a type

===========

**UserDirectory.cpp**

#include "UserDirectory.h"
#include <iostream>
#include <string>
using namespace std;

UserDirectory::UserDirectory(){
cout << "UserDirectory Constructor created\n\n";
}
UserDirectory::void setName(string x){
    name = x;
}
UserDirectory::string getName(){
    return name_;
}
UserDirectory::string name;

===========

**UserDirectory.h**

#ifndef USERDIRECTORY_H
#define USERDIRECTORY_H
#include <iostream>
#include <string>

class UserDirectory
{
    public:
    UserDirectory();
    void setName( std::string x );
    std::string getName();
    private:
    std::string name_;
};

#endif // USERDIRECTORY_H

======

**main.cpp**

#include <iostream>
#include <string>
#include "UserDirectory.h"
using namespace std;


int main(){

    UserDirectory user1;
string inputName;

cout << "Enter your name: ";
cin >> inputName;
user1.setName( inputName );
cout << "\nYou entered " << user1.getName();

    return 0;
} // end main

2 个答案:

答案 0 :(得分:3)

您将UserDirectory::放在错误的位置。范围解析运算符(::)用于解析名称的范围。 voidstring不需要解决,因为它们在外部范围内可见;只有类中的名称需要作用域解析,因此它适用于这些名称:

void UserDirectory::setName(string x){
    ...
}

string UserDirectory::getName(){
    ...
}

当你说UserDirectory::void时,你告诉编译器你的班级void中有一个UserDirectory类型,显然没有。

答案 1 :(得分:2)

您不需要单独定义name,您需要切换命名空间和类型,如下所示:

void UserDirectory::setName(string x){
    name = x;
}
string UserDirectory::getName(){
    return name_;
}

// This would be necessary if "name" were static;
// Since it is not, remove this line:
string UserDirectory::name;