Chan Kim Chan Kim - 3 months ago 14
C++ Question

error in basic c++ class declaration and object instantiation

To test a feature, I wrote a simple example codes but met with problems in the example code itself. :). I think I'm lacking some basics in C++.

// nature.cpp
#include "nature.hpp"

void nature::say_name(){
printf("I'm nature\n");
}

// nature.hpp
#include "person.hpp"

class nature{
public:
nature(){}
~nature(){}
public:
person _person;
void say_name();
}

// person.cpp
#include "person.hpp"

void person::say_it(){
printf("I'm a person\n");
}
// person.hpp
class person {
public:
person(){}
~person(){}
char name[20];
int age;
void say_it();
}

// test2.cpp
#include "nature.hpp"

main() {
nature beauty;
nature.say_it();
}


When I compile by
g++ nature.cpp person.cpp test2.cpp -o test2
, I have these error messages :

person.hpp:1: error: new types may not be defined in a return type
person.hpp:1: note: (perhaps a semicolon is missing after the definition of 'person')
nature.cpp:3: error: two or more data types in declaration of 'say_name'
person.cpp: In member function 'void person::say_it()':
person.cpp:4: error: 'printf' was not declared in this scope
person.hpp:1: error: new types may not be defined in a return type
person.hpp:1: note: (perhaps a semicolon is missing after the definition of 'person')
test2.cpp:3: error: two or more data types in declaration of 'main'


What are the errors? I can't event find the first error message means(... is private).

Answer

When you made your constructor and destructor private, you made the class non - instantiable. Put the constructor and destructor of all the classes in the public area. Couple of recommendations as well. Use std::string not char arrays. Use cout, not printf(). Constructor's and destructors don't Have to be public, but why you wouldn't want to make them public is really not something people want.

EDIT
You don't need 2 public interfaces, remove one public label (the middle one). Next, printf is declared in <stdio.h>, so to use it you need <stdio.h> or <cstdio>. Another recommendation, mark your data members private, so they are inaccessible outside the class (data members like age). Also, at the end of every class declaration, you need a semicolon:

class A
{
    //...
}; //<-- like this
Comments