我对C ++还是很陌生,所以对任何严重错误深表歉意。
问题陈述
我的代码用于数学计算,因此main.cpp / main.h进行设置,读取参数等,然后执行单独的文件/标题(称为driver.cpp / driver.h)进行计算。
要封装参数,我创建了几种用户定义的数据类型,在main.cpp中对其进行了初始化,然后将它们传递给driver.cpp中定义的函数。我希望这些参数对于driver.cpp中的函数而言是恒定的,并且我还希望对它们进行别名化以提高可读性。最好为它们一次加上别名,而不是在每个函数中都使用别名。这可能吗?
我试图制作一个简单的示例来说明我想要的,即使它无法运行,因为您不能像下面那样使用常量引用。
我想要的想法:
main.cpp
struct myStruct_t{
int a,b,c;
};
int main(int argc,char **argv){
myStruct_t myStruct;
myStruct.a=1;
myStruct.b=2;
myStruct.c=3;
driver(myStruct);
}
driver.cpp
const int &a,&b,&c;
void func1();
void func2();
driver(const myStruct_t& myStruct){
a = myStruct.a;
b = myStruct.b;
c = myStruct.c;
func1();
func2();
}
void func1(){
// do stuff with a,b,c
}
void func2(){
// do stuff with a,b,c
}
另一方面,按如下方式实现驱动程序将起作用。我不太喜欢它,因为我需要在每个函数中复制引用声明。
什么有效,但我不太喜欢:
alt_driver.cpp
void func1(const myStruct_t& myStruct);
void func2(const myStruct_t& myStruct);
driver(const myStruct_t& myStruct){
func1(myStruct);
func2(myStruct);
}
void func1(const myStruct_t& myStruct){
const int& a = myStruct.a;
const int& b = myStruct.b;
const int& c = myStruct.c;
// do stuff with a,b,c
}
void func2(const myStruct_t& myStruct){
const int& a = myStruct.a;
const int& b = myStruct.b;
const int& c = myStruct.c;
// do stuff with a,b,c
}
答案 0 :(得分:2)
除非性能是一个因素,否则我建议不要依赖全局引用变量。我建议使用功能界面访问它们。
// Create a namespace for driver.cpp
// Put all the helper functions and data in the namespace.
namespace driver_ns
{
myStruct_t const* myStructPtr = nullptr;
int const& a()
{
return myStructPtr->a;
}
int const& b()
{
return myStructPtr->b;
}
int const& c()
{
return myStructPtr->c;
}
}
using namesapce driver_ns;
void func1();
void func2();
driver(const myStruct_t& myStruct){
myStructPtr = &myStruct;
func1();
func2();
}
void func1(){
// do stuff with a,b,c, usig a(), b(), and c()
}
void func2(){
// do stuff with a,b,c, usig a(), b(), and c()
}
如果需要访问多个文件中的a
,b
和c
,请在共享的.h文件中添加功能接口,并在独立于文件的文件中实现它们使用它们的地方。
答案 1 :(得分:1)
如果可以使用指向const而不是const引用的指针,则可以进行如下操作。 (对于一个实际的解决方案,我可以自由地将通用声明分成一个头文件driver.h
。这是标准的C ++实践。)
driver.h
#ifndef DRIVER_H
#define DRIVER_H
struct myStruct_t{
int a,b,c;
};
void driver(const myStruct_t&);
void func1();
void func2();
#endif
main.cpp
#include "driver.h"
int main(int, char **){
myStruct_t myStruct;
myStruct.a=1;
myStruct.b=2;
myStruct.c=3;
driver(myStruct);
}
driver.cpp
#include "driver.h"
const int *a0,*b0,*c0;
void driver(const myStruct_t& myStruct){
a0 = &myStruct.a;
b0 = &myStruct.b;
c0 = &myStruct.c;
func1();
func2();
}
void func1(){
const int& a = *a0;
const int& b = *b0;
const int& c = *c0;
// do stuff with a,b,c, such as:
int d = a+b+c;
++d;
}
void func2(){
const int& a = *a0;
const int& b = *b0;
const int& c = *c0;
// do stuff with a,b,c, such as:
int d = a+b+c;
++d;
}
除了地址被明确存储和使用外,上面的代码与全局引用几乎相同。确实,生成的机器代码可能是相同的。
请注意,我写的是const int *a,*b,*c;
,而不是int *const a, *const b, *const c;
。后者将定义const指针,这通常很有用,但不是您想要的。而是在这里,您想要指向const的指针。