小编Asp*_*bie的帖子

在 C++ 中使用没有伙伴类/Cpp 文件的头文件是否实用

我最近选择了 C++ 作为我课程的一部分,并且我试图更深入地了解标头和类之间的合作关系。从我查找的头文件中的每个示例或教程中,它们都使用带有构造函数的类文件,然后跟进方法(如果包含它们)。但是我想知道是否可以只使用头文件来保存一组相关函数,而无需每次要使用它们时都创建该类的对象。

//main file
#include <iostream>
#include "Example.h"
#include "Example2.h"

int main()
{
    //Example 1
    Example a; //I have to create an object of the class first
    a.square(4); //Then I can call the function

    //Example 2
    square(4); //I can call the function without the need of a constructor

    std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,我创建一个对象,然后调用该函数,我使用两个文件“Example.h”和“Example.cpp”

  //Example1 cpp
    #include <iostream>
    #include "Example.h"

void Example::square(int i)
{
    i *= i;
    std::cout << i << std::endl;
}
//Example1 header
class Example
{
public:
    void square(int i); …
Run Code Online (Sandbox Code Playgroud)

c++ header class

4
推荐指数
1
解决办法
5516
查看次数

使用malloc给了我比预期更多的内存?

我正试图掌握malloc,到目前为止,我在测试和玩它时大多数都会得到意想不到的结果.

int main(int argc, char** argv)
{
    int size = 10;
    int *A;
    A = (int *)malloc(size * sizeof(int));
    for (int i = 0; i < 10000; i++)
    {
        A[i] = i;
    }
    for (int i = 0; i < 10000; i++)
    {
        printf("%d) %d\n", i, A[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

以上面的示例代码为例,代码运行时没有错误.即使我只分配A了10*int,所以我预计循环只会在遇到错误之前运行10次.如果我将循环增加到大约30-40k,那么它会遇到分段错误.但是,如果我将我的大小增加到循环量,它将始终像预期的那样工作.所以我知道如何避免这个错误..有点,我只是希望有人可以帮助解释为什么会这样.

编辑:原来我没有意识到C没有检测到越界,我被Java和C++一直照顾得太多了.我有不明确的行为,现在知道我的工作是防止它们.感谢所有回复的人.

c memory arrays malloc dynamic

2
推荐指数
1
解决办法
82
查看次数

在C++中使用类来存储和列出变量/方法是一种好习惯

我最近开始在编程中使用类,特别是在这种情况下使用C++,我试图理解实际使用它们的理想方法.理想情况下,如果确实存在这样的标准,我希望养成练习写出行业期望的习惯.我知道你可以使用类来保存对象有用的特定信息,例如汽车类.但是,诸如'Formulas()'这样的类只能存储程序其余部分可以使用的方法,或者只有一个变量类来保存​​常量,全局变量,或者只是你希望其他程序访问的任何东西.

int main()
{
    //Just used minimally to start the program
}


class Car()
{
    //Variables of a car: Model, year etc
    //Methods of a car: Such as drive(), parkUp(); refuel(); 
}

//Below here is class formalities I'm unsure about, are they okay to use this way
class Formulas()
{
    //holds a bunch of a formulas/methods almost all the classes can utilize
    //Examples below
    void ErrorCheck()
    {
        //checks input errors
    }
    void ColourChange()
    {
        //changes font colour
    }
    void Clear() …
Run Code Online (Sandbox Code Playgroud)

c++ oop class

0
推荐指数
1
解决办法
90
查看次数

标签 统计

c++ ×2

class ×2

arrays ×1

c ×1

dynamic ×1

header ×1

malloc ×1

memory ×1

oop ×1