Sign in to follow this  
Blednik

Why does this not compile?

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this