代码之家  ›  专栏  ›  技术社区  ›  Laz

VC++中的代码错误,看起来非常好的C++?

  •  1
  • Laz  · 技术社区  · 16 年前

    嘿,伙计们。查看这段示例代码。

    #include "stdafx.h"
    #include<conio.h>
    #include<string.h>
    
    class person{
    private char name[20];
    private int age;
    
    public void setValues(char n[],int a)
    {
        strcpy(this->name,n);
        this->age=a;
    }
    public void display()
    {
        printf("\nName = %s",name);
        printf("\nAge = %d",age);
    }
    };
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    person p;
    p.setValues("ram",20);
    p.display();
    getch();
    return 0;
    }
    

    我收到以下错误:

    1>------生成已启动:项目:第一个,配置:调试win32------ 1>第一个.cpp 1>c:\documents and settings\dark wraith\my documents\Visual Studio 2010\projects\first\first\first.cpp(9):错误C2144:语法错误:“char”前面应加“:”

    1>c:\documents and settings\dark wraith\my documents\Visual Studio 2010\projects\first\first\first.cpp(10):错误C2144:语法错误:“int”前面应加“:”

    1>c:\documents and settings\dark wraith\my documents\Visual Studio 2010\projects\first\first\first.cpp(12):错误C2144:语法错误:“void”前面应加“:”

    1>c:\documents and settings\dark wraith\my documents\Visual Studio 2010\projects\first\first\first.cpp(17):错误C2144:语法错误:“void”前面应加“:” =====生成:0成功,1失败,0最新,0跳过===========

    2 回复  |  直到 16 年前
        1
  •  11
  •   Naveen    16 年前

    声明的语法 public private 是错的。与其他语言不同,在C++中应该是

    class person{
    private: 
    char name[20];
     int age;
    public:
      void display();
    

        2
  •  3
  •   Alex Korban    16 年前

    在C++中, private 工作方式如下:

    class A 
    {
    private:
        void f();
        void g();
    };
    

    注意冒号。