简体   繁体   English

如何在C ++中创建类的实例

[英]How do you create an instance of a class in C++

I'm a C++ beginner. 我是C ++初学者。 I have a class and when I try to compile it says it's missing 'main'. 我有一堂课,当我尝试编译时说它缺少“主”。

What do I need to do to create an instance of this class and access its methods? 我需要怎么做才能创建此类的实例并访问其方法?

#include <string>
#include <iostream>

using namespace std;

class Account
{
      string name;
      double balance;

  public:
      Account(string n);
      Account(string n, double initial_balance);

      string get_name() const;
      double get_balance() const;

      void deposit(double amount);

      void widthdraw(double amount);

};

edit: 编辑:

Where do I put the main method? 我将主要方法放在哪里?

I have tried putting it in a different file like the following 我尝试将其放在其他文件中,如下所示

    #include <Account>
    int main(){
    Account:: Account(string n) : name(n), balance(0){}
    return 0 ;
    }

but this gives an error saying there is not Account in the directory. 但这会导致错误,指出目录中没有帐户。 I'm guessing this is because it's not compiled 我猜这是因为它没有编译

edit: 编辑:

Both files are in the same directory 两个文件都在同一目录中

account_main.cc account_main.cc

    #include<string>
    #include <iostream>
    #include "Account.cc"

    Account:: Account(string n) : name(n), balance(0){} 
    int main()
    {
        Account account("Account Name"); // A variable called "account"
        account.deposit(100.00); // Calls the deposit() function on account

        return 0 ;
    }

Account.cc Account.cc

#include<string>
#include <iostream>

using namespace std;

class Account
{
      string name;
      double balance;

  public:
      Account(string n);
      Account(string n, double initial_balance);

      string get_name() const;
      double get_balance() const;

      void deposit(double amount);

      void widthdraw(double amount);

};

All C++ programs require what's called an entry point . 所有C ++程序都需要所谓的入口点 The main() function is always the entry point for standard C++ programs. main()函数始终是标准C ++程序的入口点。 You need to provide a main() , function otherwise the linker will complain. 您需要提供main()函数,否则链接器会抱怨。 You can write a main() function in one of two ways: 您可以通过以下两种方式之一编写main()函数:

int main()
{
    return 0;
}

Or, if you are expecting command-line arguments: 或者,如果您期望使用命令行参数:

int main(int argc, char ** argv)
{
    return 0;
}

Note that void main() is not valid in C++ . 请注意, void main() 在C ++中无效 Also note that a return statement isn't strictly necessary for main() functions, but you should explicitly write one anyway, for the sake of consistency. 还要注意,对于main()函数来说,并非必须要使用return语句,但是为了保持一致性,您仍然应该明确地编写一个return语句。

C++ Standard 3.6.1 Main function [basic.start.main] C ++标准3.6.1主要功能[basic.start.main]

5. A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. 5. main中的return语句的作用是保留main函数(使用自动存储持续时间销毁所有对象)并使用返回值作为参数调用exit。 If control reaches the end of main without encountering a return statement, the effect is that of executing 如果控制在没有遇到return语句的情况下到达了main的末尾,则其结果是执行

  return 0; 

To answer your question about your latest edit: 要回答有关最新编辑的问题,请执行以下操作:

#include <Account>

int main(){ 
    Account:: Account(string n) : name(n), balance(0){} 
    return 0 ; 
} 

The form of main() is correct, but this is not how you provide class member definitions. main()的形式是正确的,但这不是您提供类成员定义的方式。 The constructor needs to be outside the main function. 构造函数必须在main函数之外。

#include <Account>

// Outside of main()
Account::Account(string n) : name(n), balance(0)
{
} 

int main()
{ 
     return 0 ; 
} 

To create an instance of Account , you declare a variable and pass all the required constructor arguments like this: 要创建Account的实例,您需要声明一个变量并传递所有必需的构造函数参数,如下所示:

int main()
{
    Account account("Account Name"); // A variable called "account"
    account.deposit(100.00); // Calls the deposit() function on account
                             // Make sure you provide a function
                             // definition for Account::deposit().
    return 0;
}

Also, check the exact file path of where class Account is. 此外,检查class Account所在的确切文件路径。 If the Account class is in a file called Account.h and is in the same folder as the file containing the main() function, then you need to use #include "Account.h" instead of #include <Account> in that file. 如果Account类位于一个名为Account.h的文件中,并且与包含main()函数的文件位于同一文件夹中,则需要在该文件中使用#include "Account.h"而不是#include <Account> For example: 例如:

#include "Account.h" // Note .h and quotes

Account::Account(string n) : name(n), balance(0)
{
} 

int main()
{
    // ...
    return 0;
}

This is actually a rather fundamental aspect of the C++ programming language. 这实际上是C ++编程语言的一个相当基本的方面。 Surely you have a book that covers this? 您肯定有一本涵盖此书的书吗? In fact, main() functions and #include statements are usually the first thing that you learn when programming in C++. 实际上, main()函数和#include语句通常是使用C ++编程时要学习的第一件事。 I highly recommend that you pick up a good C++ book and read through them and do the exercises. 我强烈建议您拿起一本不错的C ++书,并通读它们并进行练习。

For your latest edit: not Account in the directory 对于最新的编辑: not Account in the directory

try this: 尝试这个:

#include "Account.h"  //quotes, and .h


Account:: Account(string n)  //this must be outside of main, it's its own function
: name(n), balance(0) //I put these on three seperate lines but
{}                    //that's a personal choice

int main(){  //this is what the code should do when it starts
    Account person1("George"); //create a Account called person1 with the name George
    cout << person1.get_name(); //c-output person1's name.
    return 0 ; //return success (success=0)
}

as has been pointed out, you need a decent book. 正如已经指出的,您需要一本像样的书。 To answer your questions you should know the following: Classes are usually defined in .h file and implemented in .cpp or .cc file. 要回答您的问题,您应该了解以下内容:类通常在.h文件中定义,并在.cpp或.cc文件中实现。 You should have three files: Account.h, Account.cc and main.cc. 您应该具有三个文件:Account.h,Account.cc和main.cc。 You only compile the .cc files and the .h files are included in the parts of code where you need to know something about the class (ie when you are actually doing something with the class). 您仅编译.cc文件,而.h文件包含在您需要了解有关类的知识的代码部分中(即,当您实际上在对类进行某些操作时)。 If you are using g++ (linux, unix or mingw I think) you can compile the program using the following command: g++ main.cc Account.cc -o program_name 如果使用的是g ++(我认为是Linux,unix或mingw),则可以使用以下命令来编译程序:g ++ main.cc Account.cc -o program_name

main.cc: main.cc:

#include <iostream>
using namespace std;

#include "Account.h"
int main() {
  Account a("first account");

  cout << a.get_balance() << endl;
  a.deposit(100.0);
  cout << a.get_balance() << endl;

  return 0;
}

Your Account.h file should look like this: 您的Account.h文件应如下所示:

#include<string>
//#include <iostream> -- not needed here

// using namespace std; -- don't use 'using' in header files

class Account
{
  std::string name;
  double balance;

public:
    Account(std::string n);
    Account(std::string n, double initial_balance);

    std::string get_name() const;
    double get_balance() const;

    void deposit(double amount);

    void widthdraw(double amount);

};

And finally your Account.cc file should implement the class. 最后,您的Account.cc文件应实现该类。

#include "Account.h"

using namespace std;

Account::Account(string n) : name(n), balance(0.0) {}

Account::Account(string n, double initial_balance) :
name(n), balance(initial_balance) {}

string Account::get_name() const {
  return name;
}

double Account::get_balance() const {
  return balance;
}

void Account::deposit(double amount) {
  balance += amount;
}

void Account::widthdraw(double amount) {
  balance -= amount; // generously allow overdraft...
}

Hope that helps. 希望能有所帮助。

Roman 罗曼

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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