Alex Rivera | Logout

C++ - Private variables in classes

Asked 2011-04-10T16:34:58.273
10

I am trying to create a class in seperate files with private variables. So far my classes code is:

In TestClass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <string>
using namespace std;

class TestClass
{
    private:
        string hi;
    public:
        TestClass(string x);
        void set(string x);
        void print(int x);
};

#endif

In TestClass.cpp

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

TestClass::TestClass(string x)
{
    cout << "constuct " << x << endl;
}

void set(string x){
    hi = x;
}

void print(int x){
    if(x == 2)
        cout << hi << " x = two\n";
    else if(x < -10)
        cout << hi << " x < -10\n";
    else if(x >= 10)
        cout << hi << " x >= 10\n";
    else
        cout << hi << " x = " << x << endl;
}

When I try to build in Code::Blocks it says:

  • ...\TestClass.cpp: In function 'void set(std::string)':
  • ...\TestClass.cpp:12: error: 'hi' was not declared in this scope
  • ...\TestClass.cpp: In function 'void print(int)':
  • ...\TestClass.cpp:17: error: 'hi' was not declared in this scope
  • ...\TestClass.cpp:19: error: 'hi' was not declared in this scope
  • ...\TestClass.cpp:21: error: 'hi' was not declared in this scope
  • ...\TestClass.cpp:23: error: 'hi' was not declared in this scope

But when I run it (and don't build it) everything is working.

Edit
Report

1 Answer

-2
-void set(string x) {
+void TestClass:set(string x) {
answered 2011-04-10T16:37:54.857

Your Answer