• Advertisement
Sign in to follow this  

Why does this not compile?

This topic is 1353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

test.cpp:
#include <iostream>
#include <string>

using namespace std;

class Test {
private:
	string str;
public:
	void Setstr(const string &st);
	void Getstr(string &st);
};

void Test::Setstr(const string &st) {
	this->str = st;
}

void Test::Getstr(string &st) {
	st = this->str;
}

int main() {
	string s;
	Test t();
	t.Setstr("Test");
	t.Getstr(s);
	
	cout << s << endl;
	return 0;
}
Result:
$ g++ -Wall -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:25:4: error: request for member ‘Setstr’ in ‘t’, which is of non-class type ‘Test()’
  t.Setstr("Test");
    ^
test.cpp:26:4: error: request for member ‘Getstr’ in ‘t’, which is of non-class type ‘Test()’
  t.Getstr(s);
    ^
Well?

Share this post


Link to post
Share on other sites
Advertisement

Or use "Test t{}". That gives uniformity to how variables are declared and initialized.

Note that this is C++11 syntax, and may not yet be understood by all compilers, especially if you're using an older version (e.g., Visual Studio 2012 or older).  So don't be surprised if you try it and get further compilation errors.

Share this post


Link to post
Share on other sites
Well, the OP uses g++, so worst case he needs to add --std=c++11 depending on what his defaults are. Unless his gcc is really old.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement