2017-04-07 66 views
-2

我正在通過自我指令的方式追求對C++編程的興趣。我現在正在研究一些基本的東西,目前我的課題正在討論/實例化?C++。傳遞給函數。語法問題

我想讓我的主要cpp文件與標題一起編譯,並通過使用更高效的命令方法調用一些類功能。

我被卡住了,並希望得到一些幫助。我將包括這兩個文件。我只是試圖通過調用該函數從頭獲取返回值。

錯誤: main.cpp中:6.21錯誤:無法調用成員函數「沒有對象無效MyClass的:: setNumber(INT)

代碼工作時與主編譯,所以它的東西與」範圍決議運營商'我認爲。首先是main.cpp中

#include <iostream> 

#include "myClass.h" 
using namespace std; 
int main(){ 
myClass::setNumber(6); 

{ 
return number; 
} 
} 

然後我的頭文件myClass.h

// MyClass.h 
#ifndef MYCLASS_H 
#define MYCLASS_H 


class myClass { 

    private: 

     int number;//declares the int 'number' 
     float numberFloat;//declares the float 'numberFloat 


    public: 

     void setNumber(int x) { 
      number = x;//wraps the argument "x" as "number" 
     } 
     void setNumberFloat(float x) { 
      numberFloat = x; 
     } 

     int getNumber() {//defines the function within the class. 

     number += 500; 
      return number; 
     } 
     float getNumberFloat() {//defines the function 
     numberFloat *= 1.07; 
      return numberFloat; 
    } 

}; 

#endif 

任何幫助嗎?

+5

看看[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – molbdnilo

回答

2

錯誤消息說明了一切:

cannot call member function 'void myClass::setNumber(int)' without object 

您需要先創建一個對象:

myClass obj; 

然後調用類的方法,該對象上:

obj.setNumber(6); 

6將被分配到的number字段變量。