gpt4 book ai didi

c++ - 清除 C++ 构造函数中的重复代码

转载 作者:太空宇宙 更新时间:2023-11-04 14:41:55 26 4
gpt4 key购买 nike

我在 C++ 中有一个头文件,它为用户提供了几个构造函数(这是一个要求):

#ifndef IMANDEL_H_
#define IMANDEL_H_

class IMandel{

public:
IMandel();
IMandel(int aWidth, int aLength);
IMandel(int threads, int aWidth, int aLength);
//other stuff!
private:
int max_iterations, thread_count, height, width;
int* buffer;
};

#endif

因此,在我相应的 cpp 文件中,我分别实现了这些构造函数:

//default constructor
IMandel::IMandel(){
height = 10000;
width = 10000;

//this code segements gets repeated in every constructor! Messy!
max_iterations = 255;
thread_count = 1;
buffer = new int[width*height];
}

IMandel::IMandel(int aWidth, int aLength){
width = aWidth;
height = aLength;

//this code segements gets repeated in every constructor! Messy!
max_iterations = 255;
thread_count = 1;
buffer = new int[width*height];
}

IMandel::IMandel(int threads, int aWidth, int aLength){
thread_count = threads;
width = aWidth;
height = aLength;

//this code segements gets repeated in every constructor! Messy!
max_iterations = 255;
buffer = new int[width*height];
}

如您所见,我的构造函数不健康,它们到处都是重复的代码块,这太糟糕了!

在 java 中,我通过使用构造函数相互调用找到了解决此问题的方法。基本上我重新使用如下构造函数(Java 示例):

public myClass(){
this(1, 10000, 10000);
}

public myClass(int aWidth, int aLength){
this(1, aWidth, aLentgh);
}

public myClass(int threads, int aWidth, int aLength){
thread_count = threads;
width = aWidth;
height = aLength;
max_iterations = 255;
buffer = new int[width*height];
}

正如您在这个 Java 示例中看到的,各种构造函数之间没有重复的代码。问题:

  1. 有没有办法在 C++ 中实现同样的效果?
  2. 如果是这样怎么办?你能提供 sample 吗?
  3. 如果没有,您推荐什么解决方案来解决问题?

最佳答案

实际解决方案会有所不同,具体取决于您使用的 C++ 版本。

在 C++03 中,一种常见的(但不完善 - 请参阅底部的有用注释)方法是创建一个 init() 所有构造函数调用的函数。您的所有三个构造函数都可以在一行中调用这样的函数:

void IMandel::init(int threads, int aWidth, int aLength){
thread_count = threads;
width = aWidth;
height = aLength;

//this code segements gets repeated in every constructor! Messy!
max_iterations = 255;
buffer = new int[width*height];
}

//default constructor
IMandel::IMandel(){
init( 1, 10000, 10000 );
}

IMandel::IMandel(int aWidth, int aLength){
init( 1, aWidth, aLength );
}

IMandel::IMandel(int threads, int aWidth, int aLength){
init( threads, aWidth, aLength );
}

在 C++11 中,构造函数可以调用其他构造函数,正如@chris 评论的那样。您可以通过这种方式更改您的构造函数:

//default constructor
IMandel::IMandel()
: IMandel( 1, 10000, 10000 )
{
}

IMandel::IMandel(int aWidth, int aLength)
: IMandel( 1, aWidth, aLength )
{
}

IMandel::IMandel(int threads, int aWidth, int aLength){
thread_count = threads;
width = aWidth;
height = aLength;

//this code segements gets repeated in every constructor! Messy!
max_iterations = 255;
buffer = new int[width*height];
}

关于c++ - 清除 C++ 构造函数中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com