Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"expected unqualified-id before 'void'" & "string in class does not name a type" errors

Tags:

c++

string

class

I'm not sure how to implement the solution here.

The errors at compilation are:-

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 Answers

You're putting the UserDirectory:: in the wrong place. The scope resolution operator (::) is used to resolve scoping on names. void and string don't need resolution as they're visible in that outer scope; only the names inside the class need scoping resolution, so it is applied to those names:

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

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

When you say UserDirectory::void, you're telling the compiler that there is a type void within your class UserDirectory, which there obviously isn't.

like image 83
chris Avatar answered Jul 19 '26 01:07

chris


You do not need to define name separately, and you need to switch around the namespace and the type, like this:

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;
like image 21
Sergey Kalinichenko Avatar answered Jul 19 '26 00:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!