简体   繁体   中英

Error while creating a class in C++ Visual Studio 2012

I am really new to C++ so if it a is really stupid question I am sorry. I am trying to create an Object Dog but it won't allow me to pass in the name into the contractor here is the code

Main.cpp

#include <iostream>
#include <string>
#include "Dog.h"
int main(){
    std::string name = "Spike";
    Dog *dog = new Dog('Name', 2);



}

Dog.h

    #include <string>
class Dog {
public :
    std::string name;
    int age;
    Dog(std::string name , int age); 
};      

Dog.cpp

    #include "Dog.h";
#include <string>;

    Dog::Dog(std::string name, int age)
    {
        Dog::name = name;
        Dog::age = age;
    }

The error you are seeing is because you are passing single quoted Name and not the lower cased name variable. That will give you errors. However there are others.

You are trying to access the member variable name by dog::name . This is incorrect use dog.name .

So use period and not double colon.

Note: You could also use this->name = name .

You are using :: wrongly. It is for accessing static variables and methods of a class/struct or namespace.

You are trying to access object members, use either . or ->

For more info: When do I use a dot, arrow, or double colon to refer to members of a class in C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM