2017-03-17 110 views
-2

我剛開始學習cpp。我用2個構造函數創建了一個類。 當我運行在Ubuntu這個命令:g++ -Wall -g main.cpp car.cpp -o a 我得到一個錯誤按摩:C++中的構造函數錯誤

> "In file included from main.cpp:2:0: car.h:10:15: 
error: expected ‘)’ before ‘,’ token car(string,string,int); 

In file included from car.cpp:1:0: car.h:10:15: 
error: expected ‘)’ before ‘,’ token car(string,string,int); 

car.cpp:10:9: error: expected constructor, destructor, or type conversion before ‘(’ token car::car(string brand, string color, int cost){ " 

我不明白爲什麼林收到此錯誤信息,什麼是錯我的代碼? 請幫幫我。

這是我的代碼:

這是一個.h文件

#include <iostream> 
#include <string> 
#pragma once 

class car{ 

    public: 
    car(); 
    car(string,string,int); 
    int get_cost(); 
    std::string get_brand(); 
    std::string get_color(); 

    private: 
    std::string newbrand; 
    std::string newcolor; 
    int newcost; 

}; 

這是car.cpp文件:

#include "car.h" 

car::car(){ 
    this->newcost=0; 
    this->newbrand="No Brand"; 
    this->newcolor="No color"; 
} 

car::car(string brand, string color, int cost){ 
    newbrand=brand; 
    newcolor=color; 
    newcost=cost; 
} 

int car:: get_cost(){ 
    return newcost; 
} 


std::string car:: get_brand(){ 
    return newbrand; 
} 

std::string car:: get_color(){ 
    return newcolor; 
} 

這是我的主要文件:

#include <iostream> 
#include "car.h" 

int main(){ 
    car c; 
    std::cout <<c.get_brand()<< std::endl; 
    return 0; 
} 
+4

什麼是'string'?你的意思是'std :: string'? –

+0

我將它包含在h文件中,在這裏我將這個類放入其中。 –

+0

如果你正在學習C++,你可能會對我們的[很好的C++書籍](http://stackoverflow.com/q/388242/1782465)列表感興趣。 – Angew

回答

5

字符串在命名空間std中,所以喲你必須使用std :: string。

And #pragma once必須在第一行!

#pragma once 
#include <iostream> 
#include <string> 

class car{ 

    public: 
    car(); 
    car(std::string, std::string, int); 
    int get_cost(); 
    std::string get_brand(); 
    std::string get_color(); 

    private: 
    std::string newbrand; 
    std::string newcolor; 
    int newcost; 

};